﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// WMS_车牌信息下发
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WMSCarInfoCreateController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string gz_con;


        public WMSCarInfoCreateController(ILogger<WMSCreateCarInfoRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            gz_con = _configuration.GetConnectionString("GZ_WMS_DbConnection");
            _logger = loggerFactory.CreateLogger<WMSCarInfoCreateController>();

        }

        /// <summary>
        ///WMS_车牌信息下发
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostCarInfoCreate([FromBody] WMSCreateCarInfoRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            WMSCreateCarInfoResponseDto re = new WMSCreateCarInfoResponseDto();


            if (strparm.waybillNo == "")
            {
                strMsg = "waybillNo不能为空，请检查后再试！";
            }

            if (strparm.carNo == "")
            {
                strMsg = "carNo不能为空，请检查后再试！";
            }

            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic


            try
            {
                if (strMsg == "")
                {
                    var row = strparm.details;
                    foreach (var item in row)
                    {                     
                        dic = new Dictionary<string, string>();
                        dic.Add("SOREFERENCE1", item.salesOrderNo);
                        dic.Add("SOREFERENCE3", strparm.waybillNo);
                        string  sqlstr= MethodHelp.GetTranSQL("TMS0179", dic, con);//获取订单明细表SQL语句
                        DataTable check_ccode = DB.OracleQuery(sqlstr.ToString(),gz_con);//获取订单明细记录
                        if (check_ccode.Rows.Count > 0)
                        {
                            dic = new Dictionary<string, string>();
                            dic.Add("ORDERNO", check_ccode.Rows[0]["SALESORDERNO"].ToString());
                            string sqlstr_o = MethodHelp.GetTranSQL("TMS0180", dic, con);//获取订单柜号列表SQL语句
                            DataTable check_o = DB.OracleQuery(sqlstr_o.ToString(), gz_con);//获取柜号列表数据
                            if (check_ccode.Rows.Count>check_o.Rows.Count)//对比订单明细记录数是否大于柜号列表
                            {
                                List<string> strSqlList_OrderGH = new List<string>();//先插柜号列表
                                for (int i= check_ccode.Rows.Count- check_o.Rows.Count; i > 0; i--)
                                {
                                    dic = new Dictionary<string, string>();
                                    dic.Add("ORDERNO", check_ccode.Rows[0]["SALESORDERNO"].ToString());
                                    dic.Add("CABNO", check_ccode.Rows[0]["SALESORDERNO"].ToString()+ i.ToString());
                                    dic.Add("DRIVER", strparm.driverName);
                                    dic.Add("CARNO", strparm.carNo);
                                    string sqlstr_in1 = MethodHelp.GetTranSQL("TMS0182", dic, con);//获取插入柜号明细表语句
                                    if (sqlstr_in1.Trim()!=""|| sqlstr_in1.Trim()!=null)
                                    {
                                        strSqlList_OrderGH.Add(sqlstr_in1);
                                    }
                                    else
                                    {
                                        strMsg = "获取插入柜号列表明细语句失败！";
                                    }
                                }

                                //先补齐柜号列表记录
                                if (strSqlList_OrderGH.Count>0&& strMsg=="")
                                {
                                    bool A = DB.OracleExecuteNoQueryTran(strSqlList_OrderGH, gz_con);
                                    if (A)
                                    {

                                    }
                                    else
                                    {
                                        strMsg = "TMS0179 数据库插入失败";
                                    }
                                }
                            }

                            if (strMsg == "")
                            {
                                List<string> strSqlList = new List<string>();//车辆表处理
                                //插入记录后，重新获取柜号列表数据
                                dic = new Dictionary<string, string>();
                                dic.Add("ORDERNO", check_ccode.Rows[0]["SALESORDERNO"].ToString());
                                string sqlstr_o2 = MethodHelp.GetTranSQL("TMS0180", dic, con);//获取订单柜号列表SQL语句
                                DataTable check_o2 = DB.OracleQuery(sqlstr_o2.ToString(), gz_con);//获取柜号列表数据
                                if (check_o2.Rows.Count > 0)
                                {
                                    foreach (DataRow rows in check_o2.Rows)
                                    {
                                        dic = new Dictionary<string, string>();
                                        dic.Add("CABNO", rows["CABNO"].ToString());
                                        string str_gl = MethodHelp.GetTranSQL("TMS0181", dic, con);//获取车辆信息表SQL语句
                                        DataTable gh_l = DB.OracleQuery(str_gl.ToString(), gz_con);//获取车辆信息表-当前柜号
                                        if (gh_l.Rows.Count > 0)
                                        {
                                            dic = new Dictionary<string, string>();
                                            dic.Add("DRIVERNAME", strparm.driverName);
                                            dic.Add("CARNO", strparm.carNo);
                                            dic.Add("DRIVERTEL", strparm.driverTel);
                                            dic.Add("CUSADDRESS", item.cusAddress);
                                            dic.Add("CUSCONTACT", item.cusContact);
                                            dic.Add("DRIVERIDCARD", strparm.driverIdcard);
                                            dic.Add("CARRIERNAME", strparm.carrierName);
                                            dic.Add("ENDCUSTOMER", item.endCustomer);
                                            dic.Add("CABNO", rows["CABNO"].ToString());
                                            string sqlstr_ud1 = MethodHelp.GetTranSQL("TMS0184", dic, con);//获取插入柜号明细表语句
                                            if (sqlstr_ud1.Trim() != "" || sqlstr_ud1.Trim() != null)
                                            {
                                                strSqlList.Add(sqlstr_ud1);
                                            }
                                            else
                                            {
                                                strMsg = "获取插入柜号列表明细语句失败！";
                                            }

                                        }
                                        else
                                        {

                                            dic = new Dictionary<string, string>();
                                            dic.Add("ORDERNO", item.salesOrderNo);
                                            dic.Add("CABNO", rows["CABNO"].ToString());
                                            dic.Add("DRIVER", strparm.driverName);
                                            dic.Add("CARNO", strparm.carNo);
                                            dic.Add("DRIVERTEL", strparm.driverTel);
                                            dic.Add("CUSADDRESS", item.cusAddress);
                                            dic.Add("CUSCONTACT", item.cusContact);
                                            dic.Add("DRIVERIDCARD", strparm.driverIdcard);
                                            dic.Add("CARRIERNAME", strparm.carrierName);
                                            dic.Add("ENDCUSTOMER", item.endCustomer);
                                            dic.Add("WAYBILLNO", strparm.waybillNo);
                                            string sqlstr_in2 = MethodHelp.GetTranSQL("TMS0183", dic, con);//获取插入柜号明细表语句
                                            if (sqlstr_in2.Trim() != "" || sqlstr_in2.Trim() != null)
                                            {
                                                strSqlList.Add(sqlstr_in2);
                                            }
                                            else
                                            {
                                                strMsg = "获取插入柜号列表明细语句失败！";
                                            }
                                        }
                                    }

                                    //处理车辆信息表
                                    if (strMsg == "" && strSqlList.Count > 0)
                                    {
                                        bool A = DB.OracleExecuteNoQueryTran(strSqlList, gz_con);
                                        if (A)
                                        {

                                        }
                                        else
                                        {
                                            strMsg = "TMS0183 数据库插入失败";
                                        }
                                    }
                                }
                                else
                                {
                                    strMsg = "WMS获取不到订单" + check_ccode.Rows[0]["SALESORDERNO"].ToString() + "柜号列表记录！";
                                }
                            }
                        }
                        else
                        {
                            strMsg = strMsg + "--拆车单号<" + strparm.waybillNo + ">对应订单号=<" + item.salesOrderNo + "> 找不到WMS成品发货记录，请确认后再试。";
                        }                       
                    }
                  
                }               
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }
            if (strMsg=="")
            {
                re.code = 0;
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }

            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);
        }

      
    }
}
